﻿
//自定义表单设计器
(function ($, ibpm) {
    "use strict";
    $.BPM_CustmerFormDesigner = {
        init: function ($self, op) {
            var dfop = {    //脚本--数据源
                dbId: '',      // 数据主键
                dbTable: [], // 对应的表数据
                data: [{    // 选项卡数据
                    id: '1',
                    text: '主表单信息',
                    componts: []
                }]
            }

            $.extend(dfop, op || {});
            dfop.id = $self.attr('id');
            $self[0]._MCustmerFormDesigner = { dfop: dfop };
            $self.addClass('M-custmerform-designer-layout');
            var _html = '';
            _html += '<div class="M-custmerform-designer-layout-left"  id="M_custmerform_compont_list_' + dfop.id + '"></div>';

            _html += '<div class="M-custmerform-designer-layout-center">';
            _html += '<div class="M-custmerform-designer-layout-header">';
            _html += '<div class="M-custmerform-designer-tabs" id="M_custmerform_designer_tabs_' + dfop.id + '">';
            _html += '</div>';
            _html += '</div>';

            _html += '<div class="M-custmerform-designer-layout-area" id="M_custmerform_designer_layout_area_' + dfop.id + '" ></div>';
            _html += '<div class="M-custmerform-designer-layout-footer">';
            _html += '<div class="M-custmerform-designer-layout-footer-item" id="M_custmerform_tabsEdit_btn_' + dfop.id + '"><i class="fa fa-pencil-square-o"></i><span>组件布局</span></div>';
            _html += '<div class="M-custmerform-designer-layout-footer-item" id="M_custmerform_preview_btn_' + dfop.id + '"><i class="fa fa-eye"></i><span>预览表单</span></div>';
            _html += '</div>';
            _html += '<div class="M-custmerform-designer-layout-center-bg"><img src="' + top.$.rootUrl + '/Playground/Content/images/tableform.png" /></div>';

            _html += '</div>';
            _html += '<input type="hidden" id="dbId" name="dbId" value=' + dfop.dbId + ' />';
            _html += '<div class="M-custmerform-designer-layout-right" id="M_custmerform_compont_property_' + dfop.id + '"></div>';

            $self.html(_html);
            $.BPM_CustmerFormDesigner.bind($self);
            $.BPM_CustmerFormDesigner.compontinit($self);
            $.BPM_CustmerFormDesigner.compontbind($self);

            $.BPM_CustmerFormDesigner.tabbind($self);
            $.BPM_CustmerFormDesigner.renderTabs($self);
            $.BPM_CustmerFormDesigner.renderComponts($self);
        },
        // 绑定表单设计器的全局事件
        bind: function ($self) {
            // 取数据源
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            // 优化滚动条
            $('#M_custmerform_compont_list_' + dfop.id).ibpm_scroll();  //组件清单加滚动
            $('#M_custmerform_designer_tabs_' + dfop.id).ibpm_scroll();  //编辑选项卡加滚动
            $('#M_custmerform_designer_layout_area_' + dfop.id).ibpm_scroll();  //画布加滚动
            $('#M_custmerform_compont_property_' + dfop.id).ibpm_scroll();  //组件属性栏加滚动
            // 将当前数据指到“画布”
            $('#M_custmerform_designer_layout_area_' + dfop.id + ' .M-scroll-box')[0].dfop = dfop;
            
            // 预览表单
            $self.find('#M_custmerform_preview_btn_' + dfop.id).on('click', function () {
                top.custmerFormData = dfop.data;
                $.BPM_CustmerFormDesigner.saveComponts($self);
                ibpm.layerForm({
                    id: 'custmerForm_PreviewForm',
                    title: '预览当前表单',
                    url: top.$.rootUrl + '/SysEx/Scheme/PreviewForm?keyValue=custmerFormData',
                    width: 900,
                    height: 700,
                    maxmin: true,
                    btn: null
                });
            });
        },
        // 组件初始化
        compontinit: function ($self) {// 组件初始化
            // 取数据源
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            // $self是当前布局对象--在布局中取出组件清单对象进行赋值
            var $compontList = $self.find('#M_custmerform_compont_list_' + dfop.id + ' .M-scroll-box');
            // 遍历数据源的组件池
            if (dfop.components && dfop.components.length > 0) {
                $.each(dfop.components, function (i, id) {
                    var $component = $.BPM_FormComponents[id].init();   //初始化组件
                    $compontList.append($component);    //组件对象加入组件清单
                });
            }
            else {
                // 当组件数据为空时，就加载所有注册组件到清单
                $.each($.BPM_FormComponents, function (i, component) {
                    var $component = component.init();
                    $compontList.append($component);
                });
            }
            // 给组件对象，添加拖拽事件
            $compontList.find('.M-custmerform-component').draggable({
                connectToSortable: '#M_custmerform_designer_layout_area_' + dfop.id + ' .M-scroll-box',
                helper: "clone",
                revert: "invalid"
            });
            // jQuery UI 实例 - 排序（Sortable）
            $('#M_custmerform_designer_layout_area_' + dfop.id + ' .M-scroll-box').sortable({
                opacity: 0.4,
                delay: 300,
                cursor: 'move',
                placeholder: "ui-state-highlight",
                stop: function (event, ui) {
                    var $compont = $(ui.item[0]);
                    var componttype = $compont.attr('data-type');

                    if (!!componttype) {
                        //如果是第一次移入，需要对单元项进行初始化处理
                        var $designer = $compont.parents('.M-custmerform-designer-layout');
                        $compont.addClass('M-compont-item').css({ 'width': '100%' });
                        $compont.removeClass('M-custmerform-component');
                        $compont.removeAttr('data-type');
                        $.BPM_FormComponents[componttype].render($compont);
                        $compont[0].dfop.id = ibpm.newGuid();
                        $compont.trigger("click");
                    }
                    else {
                        $compont.trigger("click");
                    }
                },
                start: function (event, ui) {
                    $self.find(".M-custmerform-designer-layout-center-bg").hide();
                    var $highlight = $self.find(".ui-state-highlight");
                    $highlight.html('拖放控件到这里');
                    var $compont = $(ui.item[0]);
                    var componttype = $compont.attr('data-type');
                    if (!componttype) {
                        $highlight.css({ width: ((100 / $compont[0].dfop.proportion) + "%") });
                    }
                },
                out: function (event, ui) {
                    if (ui.helper != null) {
                        var $componts = $('.M-custmerform-designer-layout-area .M-scroll-box .M-compont-item');
                        if ($componts.length <= 1) {
                            if ($componts.length == 1) {
                                if ($componts.find('.M-compont-value').length == 0) {
                                    $(".M-custmerform-designer-layout-center-bg").show();
                                }
                            }
                            else {
                                $(".M-custmerform-designer-layout-center-bg").show();
                            }
                        }
                    }
                }
            });
        },
        // 组件事件注册
        compontbind: function ($self) {
            // $self是当前布局对象--为布局中指定的对象赋处理行为
            $self.delegate('.M-compont-item', 'click', function () {
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    $('.M-custmerform-designer-layout-area .M-scroll-box .M-compont-item').removeClass('active');
                    $this.addClass('active');
                    if ($('.M-custmerform-designer-layout').css('padding-right') == '0px') {
                        $('.M-custmerform-designer-layout').animate({ 'padding-right': '240px', speed: 2000 });
                        $('.M-custmerform-designer-layout-right').animate({ right: 0, speed: 2000 });
                    }
                    setTimeout(function () {
                        //由全局扩展，生成右侧组件属性栏HTML数据
                        $.BPM_FormComponents[$this[0].dfop.type].property($this);
                    }, 150);
                }
                return false;
            });
            // 为画布中的组件小叉，赋删除事件
            $self.delegate('.M-compont-remove i', 'click', function () {
                var $compont = $(this).parents('.M-compont-item');
                $compont.remove();
                if ($('.M-custmerform-designer-layout-area .M-scroll-box .M-compont-item').length == 0) {
                    $('.M-custmerform-designer-layout-right').animate({ right: '-240px', speed: 2000 });
                    $('.M-custmerform-designer-layout').animate({ 'padding-right': '0px', speed: 2000 });
                    $(".M-custmerform-designer-layout-center-bg").show();
                }
                else {
                    $('.M-custmerform-designer-layout-area .M-scroll-box .M-compont-item').eq(0).trigger('click');
                }
            });
        },
        // 选项卡事件绑定
        tabbind: function ($self) {
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            $self.delegate('#M_custmerform_designer_tabs_' + dfop.id + ' .M-scroll-box>div', 'click', function () {
                var $this = $(this);
                if (!$this.hasClass('active')) {
                    var $parent = $this.parent();
                    var $self = $this.parents('.M-custmerform-designer-layout');
                    var _dfop = $self[0]._MCustmerFormDesigner.dfop;

                    $parent.find('.active').removeClass('active');
                    $this.addClass('active');
                    // 保存当前选项卡组件数据
                    $.BPM_CustmerFormDesigner.saveComponts($self);
                    // 切换到新的选项卡数据
                    _dfop._currentTabId = $this.attr('data-value');
                    for (var i = 0; i < _dfop.data.length; i++) {
                        var tabItem = _dfop.data[i];
                        if (_dfop._currentTabId == tabItem.id) {
                            _dfop._currentComponts = _dfop.data[i].componts;
                        }
                    }
                    _dfop._isRenderComponts = true;
                    $.BPM_CustmerFormDesigner.renderComponts($self);
                }
            });
        },
        // 渲染选项卡
        renderTabs: function ($self) {// 渲染选项卡
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            var $tabs = $('#M_custmerform_designer_tabs_' + dfop.id + ' .M-scroll-box');
            var tabsLength = dfop.data.length;
            var index = 0;
            $tabs.html("");
            for (var i = 0; i < tabsLength; i++) {
                var tabItem = dfop.data[i];

                $tabs.append('<div data-value="' + tabItem.id + '">' + tabItem.text || '&nbsp;' + '</div>');
                if (dfop._currentTabId == tabItem.id) {
                    index = i;
                }
            }
            // 获取当前选项卡的组件数据并渲染
            if (dfop._currentTabId != dfop.data[index].id) {
                dfop._currentTabId = dfop.data[index].id;
                dfop._currentComponts = dfop.data[index].componts;
                dfop._isRenderComponts = true;
                $.BPM_CustmerFormDesigner.renderComponts($self);
            }

            if (tabsLength <= 1) {
                $self.find('.M-custmerform-designer-layout-center').removeClass('hasTab');
            }
            else {
                $self.find('.M-custmerform-designer-layout-center').addClass('hasTab');
                $tabs.find('div').eq(index).addClass('active');

                var w = 0;
                var width = $tabs.children().each(function () {
                    w += $(this).outerWidth();
                });
                $tabs.css({ 'width': w });
            }
        },
        // 渲染数据
        renderData: function ($self) {
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            var $tabs = $('#M_custmerform_designer_tabs_' + dfop.id + ' .M-scroll-box');
            var tabsLength = dfop.data.length;
            $tabs.html("");
            for (var i = 0; i < tabsLength; i++) {
                var tabItem = dfop.data[i];
                $tabs.append('<div data-value="' + tabItem.id + '">' + tabItem.text || '&nbsp;' + '</div>');
                if (i == 0) {
                    dfop._currentTabId = tabItem.id;
                    dfop._currentComponts = dfop.data[0].componts;
                    dfop._isRenderComponts = true;
                    $.BPM_CustmerFormDesigner.renderComponts($self);
                }
            }
            if (tabsLength <= 1) {
                $self.find('.M-custmerform-designer-layout-center').removeClass('hasTab');
            }
            else {
                $self.find('.M-custmerform-designer-layout-center').addClass('hasTab');
                $tabs.find('div').eq(0).addClass('active');
                var w = 0;
                var width = $tabs.children().each(function () {
                    w += $(this).outerWidth();
                });
                $tabs.css({ 'width': w });
            }
        },
        // 保存当前选项卡的组件数据
        saveComponts: function ($self) {
            // 取数据源
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            var componts = [];
            var compontsLayout = $('#M_custmerform_designer_layout_area_' + dfop.id + ' .M-scroll-box');
            compontsLayout.find('.M-compont-item').each(function () {
                var compont = $(this)[0].dfop;
                componts.push(compont);
            });
            for (var i = 0, l = dfop.data.length; i < l; i++) {
                if (dfop.data[i].id == dfop._currentTabId) {
                    dfop.data[i].componts = componts;
                    break;
                }
            }
        },
        // 渲染组件
        renderComponts: function ($self) {
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            if (dfop._isRenderComponts) {
                var compontsLayout = $('#M_custmerform_designer_layout_area_' + dfop.id + ' .M-scroll-box');
                compontsLayout.html('');
                if (dfop._currentComponts.length > 0) {
                    $self.find(".M-custmerform-designer-layout-center-bg").hide();
                    for (var i = 0, l = dfop._currentComponts.length; i < l; i++) {
                        var compontItem = dfop._currentComponts[i];
                        var $compont = $('<div class="M-compont-item"></div>');
                        $compont[0].dfop = compontItem;
                        //$compont[0].dfop.dbId = dfop.dbId;    //加标签来解决dbId传递问题
                        $compont.css({ 'width': 100 / parseInt(compontItem.proportion) + '%' });
                        $.BPM_FormComponents[compontItem.type].render($compont);
                        compontsLayout.append($compont);
                        if (i == 0) {
                            $compont.trigger("click");
                        }
                    }
                }
                else {
                    $('.M-custmerform-designer-layout-right').animate({ right: '-240px', speed: 2000 });
                    $('.M-custmerform-designer-layout').animate({ 'padding-right': '0px', speed: 2000 });
                    $(".M-custmerform-designer-layout-center-bg").show();
                }
                dfop._isRenderComponts = false;
            }
        },
        // 更新绑定的数据表字段信息
        updatedb: function ($self, op) {
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            if (dfop.dbId != op.dbId) {// 如果数据库改变,绑定字段数据重置
                dfop.dbId = op.dbId;
                for (var i = 0, l = dfop.data.length; i < l; i++) {
                    for (var j = 0, jl = dfop.data[i].componts.length; j < jl; j++) {
                        dfop.data[i].componts[j].table = '';
                        dfop.data[i].componts[j].field = '';
                    }
                }
            }
            else {
                for (var i = 0, l = dfop.dbTable.length; i < l; i++) {
                    var tablename = dfop.dbTable[i].name;
                    var flag = false;
                    for (var j = 0, jl = op.dbTable.length; i < jl; i++) {
                        if (op.dbTable[i].name == tablename) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        for (var i = 0, l = dfop.data.length; i < l; i++) {
                            for (var j = 0, jl = dfop.data[i].componts.length; j < jl; j++) {
                                if (dfop.data[i].componts[j].table == tablename) {
                                    dfop.data[i].componts[j].table = '';
                                    dfop.data[i].componts[j].field = '';
                                }
                            }
                        }
                    }
                }
            }
            dfop.dbTable = op.dbTable;
        },
        // 判定所有组件数据是否输入完整（主要是数据库绑定信息）
        validData: function ($self) {
            var dfop = $self[0]._MCustmerFormDesigner.dfop;
            var _data = {};
            var res = true;
            for (var i = 0, l = dfop.data.length; i < l; i++) {
                for (var j = 0, jl = dfop.data[i].componts.length; j < jl; j++) {
                    if (dfop.data[i].componts[j].type != 'label') {
                        var table = dfop.data[i].componts[j].table;
                        var field = dfop.data[i].componts[j].field;
                        var title = dfop.data[i].componts[j].title;
                        if (table != '' && field != '') {
                            if (!!_data[table + '_' + field]) {
                                ibpm.alert.error('【' + title + '】绑定数据表字段与【' + _data[table + '_' + field] + '】重复！');
                                res = false;
                            }
                            else {
                                _data[table + '_' + field] = title;
                            }
                        }
                        else {
                            if (dfop.data[i].componts[j].type == 'gridtable') {
                                if (table == '') {
                                    ibpm.alert.error('【表格项】请绑定数据表！');
                                    res = false;
                                }
                            }
                            else {
                                ibpm.alert.error('【' + title + '】请绑定数据表！');
                                res = false;
                            }
                        }
                    }
                }
            }
            return res;
        }
    };

    //对外暴露接口
    $.fn.ibpm_CustmerFormDesigner = function (type, op) {
        var $this = $(this);
        if (!$this.attr('id')) {
            return false;
        }
        switch (type) {
            // 初始化设计器
            case "init":
                $.BPM_CustmerFormDesigner.init($this, op);
                break;
            // 更新数据库绑定信息
            case 'updatedb':
                $.BPM_CustmerFormDesigner.updatedb($this, op);
                break;
            // 判定所有组件数据是否输入完整（主要是数据库绑定信息）
            case 'valid':
                $.BPM_CustmerFormDesigner.saveComponts($this);
                return $.BPM_CustmerFormDesigner.validData($this);
            case "get":
                $.BPM_CustmerFormDesigner.saveComponts($this);
                var dfop = $this[0]._MCustmerFormDesigner.dfop;
                var res = {
                    dbId: dfop.dbId,
                    dbTable: dfop.dbTable,
                    data: dfop.data
                };
                $.each(res.data, function (index, com) {
                    var CurrCom = [];
                    var i = 0;
                    $.each(com.componts, function (index, item) {
                        if (item.type == 'upload') {
                            if (i == 0) {
                                CurrCom.push(item);
                                i = 101;
                            }
                        }
                        else
                            CurrCom.push(item);
                    });
                    com.componts = CurrCom;
                });
                return res;
            case "set":
                var dfop = $this[0]._MCustmerFormDesigner.dfop;
                dfop.dbId = op.dbId;
                dfop.dbTable = op.dbTable;
                dfop.data = op.data;
                $.BPM_CustmerFormDesigner.renderData($this);
                break;
        }
    };

})(jQuery, top.ibpm);
